﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.EF;
using MaterialDesignExtensions.Controls;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using System.Windows.Controls;
using Masuit.Tools.Models;
using EntranceGuardManager.Modules.Main.Views;
using System.ComponentModel;
using Microsoft.EntityFrameworkCore;
using System.Threading;
using AJWPFAdmin.Core.Excel;
using System.Linq.Expressions;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using AJWPFAdmin.Core.Models.EF.Tables;
using DocumentFormat.OpenXml.Math;
using AJWPFAdmin.Core.Components.Views;
using AJWPFAdmin.Modules.Common.Views;
using Masuit.Tools.Reflection;
using AJWPFAdmin.Services;

namespace EntranceGuardManager.Modules.Main.ViewModels
{

    public class EmiRiseRecordListViewModel : BindableBase, INavigationAware
    {
        //private EmiRiseRecordExportConfig _exportConfig;
        //public EmiRiseRecordExportConfig ExportConfig
        //{
        //    get { return _exportConfig; }
        //    set { SetProperty(ref _exportConfig, value); }
        //}

        private AJTableFetchOptions _fetchOptions;

        public AJTableFetchOptions FetchOptions
        {
            get
            {
                return _fetchOptions;
            }
            set
            {
                SetProperty(ref _fetchOptions, value);
            }
        }

        private List<AJTableColumnItem> _columns;

        public List<AJTableColumnItem> Columns
        {
            get { return _columns; }
            set { SetProperty(ref _columns, value); }
        }


        private AJTableSearchFormConfig _formConfig;
        public AJTableSearchFormConfig FormConfig
        {
            get { return _formConfig; }
            set { SetProperty(ref _formConfig, value); }
        }

        private DelegateCommand<DataGridRow> _loadingRowCmd;
        public DelegateCommand<DataGridRow> LoadingRowCmd =>
            _loadingRowCmd ?? (_loadingRowCmd = new DelegateCommand<DataGridRow>(ExecuteLoadingRowCmd));

        void ExecuteLoadingRowCmd(DataGridRow row)
        {

        }

        private DelegateCommand<EmiRiseRecord> _editCmd;
        public DelegateCommand<EmiRiseRecord> EditCmd =>
            _editCmd ?? (_editCmd = new DelegateCommand<EmiRiseRecord>(ExecuteEditCmd));

        void ExecuteEditCmd(EmiRiseRecord parameter)
        {
            var @params = new DialogParameters
            {
                { "data", parameter },
                //{ "category", _navParamType },
            };
            _dialogSvc.ShowDialog(nameof(EmiRiseRecordForm), @params, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    FetchOptions.RequestRefresh(false);
                }
            });
        }


        private DelegateCommand<EmiRiseRecord> _deleteCmd;
        public DelegateCommand<EmiRiseRecord> DeleteCmd =>
            _deleteCmd ?? (_deleteCmd = new DelegateCommand<EmiRiseRecord>(ExecuteDeleteCmd));

        async void ExecuteDeleteCmd(EmiRiseRecord parameter)
        {
            var confirm = await CommonUtil.ShowConfirmDialogAsync(new ConfirmationDialogArguments
            {
                Title = "删除确认",
                Message = parameter.Synchronized ? "该条数据已经和线上接口同步,是否继续删除?" : $"即将删除 {parameter.CarNo} ?"
            });

            if (confirm)
            {
                db.EmiRiseRecords.Remove(parameter);
                await db.SaveChangesAsync();

                FetchOptions.RequestRefresh(false);
            }
        }

        //private DelegateCommand<string> _toggleExportConfigCmd;
        //public DelegateCommand<string> ToggleExportConfigCmd =>
        //    _toggleExportConfigCmd ?? (_toggleExportConfigCmd = new DelegateCommand<string>(ExecutetoggleExportConfigCmd));

        //void ExecutetoggleExportConfigCmd(string parameter)
        //{
        //    ExportConfig.Open = parameter.Equals("true", StringComparison.OrdinalIgnoreCase);
        //}

        //private DelegateCommand _exportCmd;
        //public DelegateCommand ExportCmd =>
        //    _exportCmd ?? (_exportCmd = new DelegateCommand(ExecuteExportCmd));

        //void ExecuteExportCmd()
        //{
        //    FetchOptions.RequestExport();
        //}

        private IDialogService _dialogSvc;
        private DbService db;
        private SystemUserService _sysUserSvc;


        public EmiRiseRecordListViewModel(DbService dbIns,
            SystemUserService sysUserSvc,
            IEventAggregator eventAggregator, IDialogService dialogSvc)
        {
            _sysUserSvc = sysUserSvc;
            _dialogSvc = dialogSvc;
            //eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>().Subscribe(() =>
            //{
            //    Loading = false;
            //    ExportProgress.Loading = false;
            //});

            //ExportConfig = new EmiRiseRecordExportConfig();

            FetchOptions = new AJTableFetchOptions
            {
                //ExportWithCurrentColumns = true,
                FetchOnLoaded = false,
                //ExportFileName = $"{_navParamType}台账记录导出",
                Handle = async (formCfg, pageCfg) =>
                {

                    var syncFormSchema = FormConfig.Schemas.FirstOrDefault(p => p.Field == nameof(EmiRiseRecord.Synchronized));

                    var syncFlag = syncFormSchema.Value == null ? new int?() : (int)syncFormSchema.Value;

                    var name = FormConfig.Schemas
                .FirstOrDefault(p => p.Field == nameof(EmiRiseRecord.CarNo)).Value?.ToString();

                    //var dates = FormConfig.Schemas
                    //    .FirstOrDefault().Value as ObservableCollection<DateTime?>;

                    //var start = dates.FirstOrDefault();
                    //var end = dates.LastOrDefault();

                    var list = await db.EmiRiseRecords
                    .LikeOrLike(name, p => p.CarNo)
                    .FilterBoolean(syncFlag, p => p.Synchronized)
                    .OrderByDescending(p => p.CreateDate)
                    .ToPagedListAsync(pageCfg.Current, pageCfg.PageSize);

                    return new AJTableFetchResult
                    {
                        Total = list.TotalCount,
                        HasNext = list.HasNext,
                        Rows = list.Data
                    };
                }
            };

            FormConfig = new AJTableSearchFormConfig
            {
                Schemas = new ObservableCollection<AJTableSearchFormSchema>
                {
                    new AJTableSearchFormSchema
                    {
                        Label = "车牌号",
                        Field = nameof(EmiRiseRecord.CarNo),
                        Type = AJTableSchemaType.Input,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "是否同步",
                        Field = nameof(EmiRiseRecord.Synchronized),
                        Type = AJTableSchemaType.Select,
                        IsPopular = true,
                        Options = new ObservableCollection<AJTableFormSchemaItemOptions>
                        {
                            new AJTableFormSchemaItemOptions
                            {
                                Label = "已同步",
                                Value = 1
                            },
                            new AJTableFormSchemaItemOptions
                            {
                                Label = "未同步",
                                Value = 0
                            }
                        }
                    },
                    //new AJTableSearchFormSchema
                    //{
                    //    Label = "进出筛选",
                    //    Field = nameof(EmiRiseRecord.ShipStartDate),
                    //    Type = AJTableSchemaType.Select,
                    //    IsPopular = true,
                    //    Options = new ObservableCollection<AJTableFormSchemaItemOptions>
                    //    {
                    //        new AJTableFormSchemaItemOptions
                    //        {
                    //            Label = "未出场",
                    //            Value = 0
                    //        },
                    //        new AJTableFormSchemaItemOptions
                    //        {
                    //            Label = "已出场",
                    //            Value = 1
                    //        }
                    //    }
                    //},
                    //new AJTableSearchFormSchema
                    //{
                    //    Labels = new string[]{ "入厂日期","出厂日期" },
                    //    Field = nameof(EmiRiseRecord.CreateDate),
                    //    Type = AJTableSchemaType.RangePicker,
                    //    Value = new ObservableCollection<DateTime?>( new DateTime?[2]
                    //    {
                    //        DateTime.Today,
                    //        DateTime.Today.AddDays(1).AddSeconds(-1)
                    //    }),
                    //    IsPopular = true,
                    //},
                },
                AdvFilterVisibility = System.Windows.Visibility.Collapsed,
                ExportVisibility = System.Windows.Visibility.Collapsed,
            };

            db = dbIns;
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            //navigationContext.Parameters.TryGetValue("params", out _navParamType);

            var columns = new List<AJTableColumnItem>
            {
                new AJTableColumnItem
                {
                    Title = "操作",
                    CustomTemplate = new AJTableCustomTemplate
                    {
                        Key = "TableOperatioin"
                    },
                    Fixed = AJTableColumnFixedType.Right,
                    Width = new DataGridLength(160),
                    IsExport = false
                },

            };

            columns.AddRange(_emiRiseColumns.ToList());
            Columns = columns;

            // 延迟一下, 不然因为表格没准备好无法触发刷新
            await Task.Delay(600);

            FetchOptions.RequestRefresh(false);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            _sysUserSvc.SaveColumnsConfig($"{nameof(EmiRiseRecordListViewModel).ToLower()}",
                Columns.Where(p => p.Visible).Select(p => p.Title).ToArray());
        }


        private readonly static List<AJTableColumnItem> _emiRiseColumns = new List<AJTableColumnItem> {

                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.CarNo),
                        Title = "车牌号码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.Color),
                        Title = "车牌颜色",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.VIN),
                        Title = "VIN",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.FuelType),
                        Title = "燃油类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.EmissionStandard),
                        Title = "排放标准",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.ExceedInfo),
                        Title = "超标原因",
                    },
                     new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.OverproofVerifyResult),
                        Title = "超标核实结果",
                    },
                     new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.Remark),
                        Title = "备注信息",
                    },
                      new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.ExceedFlag),
                        Title = "是否解除",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                var flag = (int)val;
                                return flag == 0 ? "未解除" : flag == 1 ? "已解除" : "未核实";
                            }
                        }
                    },
                       new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.StartTime),
                        Title = "下发时间",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd");
                            }
                        }
                    },
                         new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.EndTime),
                        Title = "解除时间",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd");
                            }
                        }
                    },
                         new AJTableColumnItem
                    {
                        DataIndex = nameof(EmiRiseRecord.Synchronized),
                        Title = "是否已同步",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已同步" : "未同步";
                            }
                        }
                    },
                    //new AJTableColumnItem
                    //{
                    //    DataIndex = nameof(EmiRiseRecord.ShipStartDate),
                    //    Title = "进厂日期",
                    //    Formatter = new AJTableColumnFormatter
                    //    {
                    //        Handler = (val) =>
                    //        {
                    //            return val == null ? "--"
                    //            : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                    //        }
                    //    }
                    //},
                    //new AJTableColumnItem
                    //{
                    //    DataIndex = nameof(EmiRiseRecord.ShipEndDate),
                    //    Title = "出厂日期",
                    //    Formatter = new AJTableColumnFormatter
                    //    {
                    //        Handler = (val) =>
                    //        {
                    //            return val == null ? "--"
                    //            : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                    //        }
                    //    }
                    //},

            };

    }


}
